package il.ac.tau.cvws.scrabblesidekick.server.servlet;

import il.ac.tau.cvws.scrabblesidekick.server.servlet.exception.CommException;
import il.ac.tau.cvws.scrabblesidekick.server.servlet.multipart.MultipartMap;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.request.RequestPayload;
import il.ac.tau.cvws.scrabblesidekick.shared.comm.response.ResponsePayload;
import il.ac.tau.cvws.scrabblesidekick.shared.constant.CommConstants;

import java.io.IOException;
import java.io.ObjectOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ScrabbleSidekickServlet extends HttpServlet
{	
	private static final long serialVersionUID = 1L;

	public RequestPayload getRequestPayload(HttpServletRequest request) throws ServletException, IOException, CommException
	{
		MultipartMap map = null;
		
		try
		{
			map = new MultipartMap(request, this);
		}
		catch (ClassNotFoundException e1)
		{
			throw new CommException(CommException.INVALID_REQUEST_PARAM);
		}
		
		RequestPayload data = (RequestPayload)map.getObject(CommConstants.PAYLOAD);
		
		return data;
	}
	
	public void sendResponsePayload(HttpServletResponse response, ResponsePayload payload) throws IOException
	{	
		response.setContentType("application/octet-stream");

		ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
		
		out.writeObject(payload);
		out.flush();
		out.close();
	}
}
